<?php
/**
 * ChangePasswordForm model class file.
 *
 * @package   models
 * @since     1.0
 * @filesource
 */

/**
 * ChangePasswordForm class
 * 
 * ChangePasswordForm is a Form class. 
 * It is the data structure for keeping change password form data. It is used by 
 * UserController.actionChangePassword.
 * Note: this class is used to allow user change himself's password.
 * 
 * @property string $oldPassword
 * @property string $newPassword
 * @property string $comfirmedPassword
 */
class ChangePasswordForm extends CFormModel
{
	/**
	 * The Old password in the form
	 * @var string
	 */
	public $oldPassword;
	
	/**
	 * The New password in the form
	 * @var string
	 */
	public $newPassword;
	
	/**
	 * The confirm new password in the form.
	 * @var string
	 */
	public $comfirmedPassword;

	/**
	 * Declares the validation rules.
	 * 
	 * The rules will be used when requesting validation by call self.validate().
	 * Many class method will call self.validate(), eg: CActiveRecord.save().
	 * 
	 * The rules state that username and password are required,
	 * and oldPassword needs to be authenticated.
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		return array(
			// username and password are required
			array('oldPassword, newPassword, comfirmedPassword', 'required'),
			// newPassword and comfirmedPassword should be same
			array('newPassword', 'compare', 'compareAttribute'=>'comfirmedPassword'),
			// oldPassword needs to be authenticated
			array('oldPassword', 'authenticate'),
		);
	}

	/**
	 * Declares attribute labels.
	 * This will be used to render label on page.
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			// label of username and password will be automatically generated according to the attribute name.
		);
	}

	/**
	 * Authenticates the password.
	 * This is the self-defined validator - 'authenticate' and is declared in rules().
	 * It will be used to authenticate the identity of a user.
	 * 
	 * @param string $attribute
	 * @param array $params
	 */
	public function authenticate($attribute,$params)
	{
		// If there is any other validation error, this validation will not be carried out.
		if(!$this->hasErrors())
		{
			// create identity to perform authentication
			$identity=new UserIdentity(Yii::app()->user->name,$this->oldPassword);
			if(!$identity->authenticate())
				// Add validation errors to the error array if authentication failed.
				$this->addError('oldPassword','Old password is incorrect.');
		}
	}
}
